const multer = require('multer');

// 生成随机数
function random(min,max) {
    return Math.floor(Math.random() * (max - min) + min);
}

const storage = multer.diskStorage({
    // 设置文件存储路径
    destination: function (req, file, cb) {
        cb(null, './data/photo');
    },
    // 设置文件名
    filename: function (req, file, cb) {
        // 获取文件扩展名
        let type = file.originalname.replace(/.+\./, '.');
        cb(null, file.fieldname + '-' + Date.now() + random(1 - 50) + type);
    }
});

const upload = multer({ storage: storage });

module.exports = function (app) {
    // 注意这里的逗号分隔
    app.post('/profile', upload.single('file'), function(req, res, next) {
        console.log(req.file.filename);
        
        let name = req.file.filename
        let src =  '/photo/' + name;
        res.send({
            code: 200,
            message: 'ok',
            src: src
        });
    });
};